#include "tank.h"
#include <cmath>

#define ROTATE_BLOCK    100
#define DRIVE_BLOCK    25
#define TANK_SPEED      2.45

Tank::Tank()
{
	//ctor
}

Tank::~Tank()
{
	//dtor
}

i32 Tank::Render()
{
	SDL_Rect dst;
	dst.x = px;
	dst.y = py;
	visual.frames[current_frame].surface[angle]->format->Amask = 0xFF000000;
	SDL_SetAlpha (  visual.frames[current_frame].surface[angle], SDL_SRCALPHA | SDL_SRCCOLORKEY, 0xFF );
	dst.x -= ( visual.frames[current_frame].surface[angle]->w - visual.w ) / 2;
	dst.y -= ( visual.frames[current_frame].surface[angle]->h - visual.h ) / 2;
	SDL_BlitSurface ( visual.frames[current_frame].surface[angle], NULL, g_screen, &dst );
	DisplayBarrel();
	return 1;
}

void Tank::DisplayBarrel()
{
	Graphics360 *g = ( Graphics360 * ) RES->GET ( "barrel" );
	SDL_Rect dst;
	dst.x = px;
	dst.y = py;
	dst.x -= ( visual.frames[current_frame].surface[angle]->w - visual.w ) / 2;
	dst.y -= ( visual.frames[current_frame].surface[angle]->h - visual.h ) / 2;
	// calc barrel angle
	i32 cx = *mousex - dst.x - g->spr.w / 2 ;
	i32 cy = dst.y - *mousey + g->spr.h / 2;
	double len = sqrt ( cx * cx + cy * cy );
	double sin = cy / len;
	double cos = cx / len;
	double d_anglec = acos ( cos ) * 180 / 3.14;
	double d_angles = asin ( sin ) * 180 / 3.14;
	double result = d_anglec;

	if ( d_angles < 0 ) {
		result = 360 - d_anglec;
	}

	dst.x -= ( g->spr.w - visual.w ) / 2;
	dst.y -= ( g->spr.h - visual.h ) / 2;

	if ( result > 360 ) {
		result -= 360;
	}

	result -= 90;
	i32 ang = ( i32 ) result;

	if ( ang < 0 ) {
		ang = 359 + ang;
	}

	if ( ang > 359 ) {
		ang = ang % 359;
	}

	current_barrel_angle = ang;
	dst.x -= ( g->spr.surface[ang]->w - g->spr.w ) / 2;
	dst.y -= ( g->spr.surface[ang]->h - g->spr.h ) / 2;
	SDL_BlitSurface (  g->spr.surface[ang], NULL, g_screen, &dst );
}

i32 Tank::SetAngle ( i32 ang )
{
	if ( ang < 0 )
	{
		while ( ang < 0 ) {
			ang += 360;
		}
	}

	if ( ang > 359 ) {
		ang = ang % 359;
	}

	angle = ang;
	return 1;
}

i32 Tank::Rotate ( u32 dir )
{
	static u32 last_rotated = 0;

	if ( SDL_GetTicks() - ROTATE_BLOCK  <= last_rotated ) {
		return 0;
	}

	last_rotated = SDL_GetTicks();

	if ( !dir ) {
		angle -= 1;
	}
	else {
		angle += 1;
	}

	if ( angle >= ANGLES )
	{
		angle = 0;
	}

	if ( angle < 0 )
	{
		angle = ANGLES - 1;
	}

	return 1;
}

i32 Tank::Drive ( u32 dir )
{
	static u32 last_drive = 0;

	if ( SDL_GetTicks() - DRIVE_BLOCK  <= last_drive ) {
		return 0;
	}

	last_drive = SDL_GetTicks();
	double drive_angle = angle * ( 360 / ANGLES) - 90;

	if ( !dir )
	{
		drive_angle -= 180;
	}

	if ( angle < 0 ) {
		angle += 360;
	}

	double x_mov, y_mov;
	x_mov = cos ( drive_angle * 3.14 / 180 ) * TANK_SPEED;
	y_mov = sin ( drive_angle * 3.14 / 180 ) * TANK_SPEED;
	px += x_mov;
	py += y_mov;
	return 1;
}
